package com.vpx.server.controller.system;

import com.vpx.server.bean.order.system.AttachDownLoadOrder;
import com.vpx.server.bean.order.system.AttachIdsOrder;
import com.vpx.server.bean.order.system.AttachUploadOrder;
import com.vpx.server.bean.result.system.AttachUploadResult;
import com.vpx.server.bean.result.system.SysAttachListResult;
import com.vpx.server.framework.authority.AuthPoicy;
import com.vpx.server.framework.authority.RequestAuth;
import com.vpx.server.framework.base.ResultMsg;
import com.vpx.server.framework.exception.BizException;
import com.vpx.server.service.system.SysAttachService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author denglw
 * @title: vpx
 * @module system
 * @description: 附件管理
 * @date 2021/9/16 10:48
 */
@RestController
@RequestMapping(value = "/api/sys/attach")
@Api(tags = "附件管理")
public class SysAttachController {
    private static final Logger logger = LoggerFactory.getLogger(SysAttachController.class);
    @Autowired
    private SysAttachService sysAttachService;

    @PostMapping(value = "/upload")
    @ApiOperation(value = "上传文件")
    public ResultMsg<AttachUploadResult> upload(@RequestParam @ApiParam(value = "文件", name = "file") MultipartFile file) {

        String fileName = file.getOriginalFilename();
        AttachUploadOrder order = new AttachUploadOrder();
        order.setFileName(fileName);
        try {
            order.setFileInputStream(file.getInputStream());
        } catch (IOException e) {
            logger.error(e.getStackTrace().toString());
            return ResultMsg.fail("请选择需要上传的文件");
        }
        return sysAttachService.upload(order);
    }

    @GetMapping(value = "/download")
    @ApiOperation(value = "下载文件")
    public void download(@RequestParam @ApiParam(value = "附件ID", name = "attachId") String attachId, HttpServletResponse response) {
        AttachDownLoadOrder order = new AttachDownLoadOrder();
        order.setAttachId(attachId);
        ResultMsg<AttachUploadResult> result = sysAttachService.download(order);
        if (!result.isSuccess()) {
            logger.info("文件数据不存在!");
//            return result;
        } else {
            try {
                if(result.getData().getFileName().contains("svg")) {
                    response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(result.getData().getFileName(), "UTF-8"));
                    response.setHeader("Content-Type", "image/svg+xml");
                } else {
                    response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(result.getData().getFileName(), "UTF-8"));
                }

                OutputStream os = response.getOutputStream();
                byte[] b = new byte[100];
                int len;
                FileInputStream fileInputStream = new FileInputStream(new File(result.getData().getFileUrl()));
                while ((len = fileInputStream.read(b)) > 0) {
                    os.write(b, 0, len);
                }
                fileInputStream.close();
//                return result;
            } catch (Exception e) {
            	e.printStackTrace();
                logger.error(e.getStackTrace().toString());
                throw new BizException("文件下载发生异常!");
//                return ResultMsg.fail(null, e.getMessage());
            }
        }
    }
    @GetMapping("findList")
    @ApiOperation("查询附件列表")
    @RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg<SysAttachListResult> findAttachList(AttachIdsOrder order) {
        return sysAttachService.findAttachList(order);
    }
}
